import { UserProfile, UserProfileResponse, UserResponse } from '@/types/data'
import request from '@/utils/request'
import { AppThunk } from '../index'
import { setEditUser, setUpdateEditUser, setUser } from '../modules/profile'

// 3. 异步action
export const getUserAction = (): AppThunk => {
  return async (dispatch, getState) => {
    const res: UserResponse = await request.get('/user')
    // console.log('res:', res)

    dispatch(setUser(res.data))

  }
}

export const getEditUserAction = (): AppThunk => {
  return async (dispatch, getState) => {
    const res: UserProfileResponse = await request.get('/user/profile')
    // console.log('res:', res)

    dispatch(setEditUser(res.data))
  }
}

/**
 * 更新用户信息：{name ,intro, gender, birthday, photo} => 可以部分传入，传啥就更新啥
 * @param userInfo 
 * @returns 
 */
export const updateUserProfileAction = (userInfo: Partial<UserProfile>): AppThunk => {
  return async (dispatch, getState) => {
    // 1. 数据库更新
    await request.patch('/user/profile', userInfo)
    // 2. redux更新
    dispatch(setUpdateEditUser(userInfo))
  }
}

export const uploadPhotoAction = (fm: FormData): AppThunk => {
  return async (dispatch, getState) => {
    // 1. 把头像上传保存到服务器，返回头像的地址
    const res = await request.patch('/user/photo', fm)
    // console.log('res', res.data.photo)

    // 2. 存储头像
    dispatch(updateUserProfileAction({ photo: res.data.photo }))
  }
}
